<template>
  <div>
    <sec-form
      ref="formRef"
      :hideProp="hideProp"
      :ruleForm="ruleForm"
      :formData="formData"
      :rules="rules"
      :span="12"
      :optionData="optionData"
    >
      <template v-slot:vChannelId>
        <div>
          <el-input
            v-model="ruleForm.vChannelId"
            :placeholder="$t('请输入群会话ID，获取位置：群设置>二维码>群ID')"
          ></el-input>
          <el-button
            type="text"
            icon="el-icon-warning-outline"
            size="mini"
            style="color: rgb(255 160 54); white-space: pre-line; width: 100%; text-align: left"
            >{{ $t("需要将发送账号加入群会话中，否则触达消息无法送达") }}</el-button
          >
        </div>
      </template>

      <template v-slot:content>
        <!-- <button @click="previewData">print html</button> -->
        <div>
          <mavon-editor
            v-if="true"
            v-model="ruleForm.content"
            ref="markdownEditor"
            :toolbars="markdownEditorProp.toolbars"
            :autofocus="false"
            @imgAdd="$imgAdd"
          >
            <template slot="left-toolbar-before">
              <button
                type="button"
                @click.stop="$toggle_imgLinkAdd('imagelink')"
                class="op-icon fa fa-mavon-picture-o dropdown dropdown-wrapper"
                aria-hidden="true"
                :title="$t('添加图片链接')"
              ></button>
              <span class="op-icon-divider"></span>
            </template>
          </mavon-editor>
        </div>
      </template>
      <template v-slot:msgTemplatePreview>
        <iframe
          id="msgTemplatePreviewIframe"
          :src="iframeUrl"
          frameborder="0"
          ref="msgTemplatePreviewRef"
          style="border: 1px solid #dcdfe6; border-radius: 4px; width: 100%; height: 300px"
        >
        </iframe>
      </template>
      <template v-slot:dcFormPreview>
        <!-- <div
          style="
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            width: 100%;
            height: 90px;
            color: #fa8919;
            background-color: #eee;
          "
        >
          {{ $t("DC模板预览开发中，您可以点击页面下方预览按钮向自己发送一份消息进行预览") }}
        </div> -->
        <el-input type="textarea" :rows="4" placeholder="" v-model="ruleForm.dcFormPreview" :readonly="true">{{
          ruleForm.dcFormPreview
        }}</el-input>
        <el-button
          type="text"
          icon="el-icon-warning-outline"
          size="mini"
          style="color: rgb(255 160 54); white-space: pre-line; width: 100%; text-align: left"
          >{{ $t("DC模板预览仅作为数据预览，具体效果请点击下方预览按钮进行查看") }}</el-button
        >
      </template>
      <template v-slot:variablesList>
        <div>
          <variables-list
            ref="variablesListRef"
            :templateContent="templateMap.get(ruleForm.dcFormId) ? templateMap.get(ruleForm.dcFormId).content : ''"
            :variables="templateMap.get(ruleForm.dcFormId) ? templateMap.get(ruleForm.dcFormId).variables : ''"
            @getVariables="getVariables"
          ></variables-list>
        </div>
      </template>
      <template v-slot:operation>
        <el-button @click="save">{{ $t("保存") }}</el-button>
        <el-tooltip class="item" effect="dark" :content="$t('向自己发一份触达，用以预览效果')" placement="top-start">
          <el-button type="primary" @click="previewTouchSource">{{ $t("预览") }}</el-button>
        </el-tooltip>
      </template>
    </sec-form>
  </div>
</template>

<script>
import {
  touchInsertApi,
  dcFromListApi,
  dcFormDetailApi,
  dcSenderListApi,
  previewTouchApi,
  detailTaskApi,
} from "api/dataCenter.js";
import { validContent, validInteger, validReceiver, validVChannelId } from "utils/validate.js";
import VariablesList from "views/touch/variablesList";

export default {
  components: { VariablesList },
  props: { touchId: Number },
  data() {
    return {
      ruleForm: {
        msgChannel: 1,
        title: "",
        followId: "",
        exclusive: 0,
        notifyUrl: "",
        dcFormId: "",
        msgAccountId: "",
        receiver: "",
        receiverOrVchannelId: true,
        vChannelId: "",
        content: "",
        variables: "",
      },
      formData: [
        {
          type: "text",
          clearable: true,
          filterable: true,
          label: this.$t("任务标题"),
          prop: "title",
        },
        {
          type: "text",
          clearable: true,
          filterable: true,
          label: this.$t("消息跟催ID"),
          prop: "followId",
          span: 12,
        },
        {
          type: "radio",
          clearable: true,
          filterable: true,
          label: this.$t("任务是否排他"),
          prop: "exclusive",
          span: 12,
          optionData: this.$store.state.dictionary.exclusive,
        },
        {
          type: "text",
          clearable: true,
          filterable: true,
          label: this.$t("回调url"),
          prop: "notifyUrl",
          span: 24,
        },
        {
          type: "select",
          clearable: true,
          filterable: true,
          label: this.$t("D-Chat模版"),
          prop: "dcFormId",
          placeholder: this.$t("请输入模板ID"),
          span: 24,
          remote: true,
          remoteMethod: (query) => {
            this.getDcFormOption(query, "");
          },
          change: (val) => {
            console.log("change", val);
            this.ruleForm.dcFormPreview = this.templateMap.get(val) ? this.templateMap.get(val).content : "";
          },
        },
        {
          type: "select",
          clearable: true,
          filterable: true,
          label: this.$t("发送账号"),
          prop: "msgAccountId",
          span: 24,
        },
        {
          type: "radio",
          clearable: true,
          filterable: true,
          label: this.$t("接收方式"),
          prop: "receiverOrVchannelId",
          span: 12,
          optionData: this.$store.state.dictionary.receiverOrVchannelId,
        },
        {
          type: "slot",
          clearable: true,
          filterable: true,
          label: this.$t("群会话ID"),
          prop: "vChannelId",
          span: 24,
        },
        {
          type: "textarea",
          clearable: true,
          rows: 4,
          label: this.$t("任务接收者"),
          span: 24,
          prop: "receiver",
          placeholder: this.$t("请输入账号（邮箱前缀）多个账号请使用英文逗号分隔；示例：zhangsan,lisi,wangwu,laoliu"),
        },
        {
          type: "slot",
          prop: "content",
          span: 24,
          label: this.$t("任务内容"),
        },
        {
          type: "slot",
          clearable: true,
          label: this.$t("DC模板预览"),
          prop: "dcFormPreview",
          span: 24,
          disabled: true,
        },
        {
          type: "slot",
          label: this.$t("模版变量"),
          prop: "variablesList",
          span: 24,
        },
        {
          type: "slot",
          prop: "operation",
          style: { "text-align": "center" },
          span: 24,
        },
      ],
      hideProp: {},
      optionData: {
        dcFormId: [],
        msgAccountId: [],
      },
      rules: {
        title: [{ required: true, message: this.$t("请输入任务标题"), trigger: "blur" }],
        followId: [{ validator: validInteger, trigger: "blur" }],
        msgAccountId: [{ required: true, message: this.$t("请选择发送账号"), trigger: "blur" }],
        vChannelId: [{ required: true, validator: validVChannelId, trigger: "blur" }],
        receiver: [{ required: true, validator: validReceiver, trigger: "blur" }],
        content: [{ required: true, validator: validContent, trigger: "blur" }],
      },
      markdownEditorProp: {
        toolbars: {
          bold: true, // 粗体
          italic: true, // 斜体
          header: false, //标题
          underline: false, // 下划线
          strikethrough: true, // 中划线
          mark: false, // 标记
          superscript: false, // 上角标
          subscript: false, // 下角标
          quote: false, // 引用
          ol: true, // 有序列表
          ul: true, // 无序列表
          link: true, // 链接
          imagelink: false, // 图片链接
          code: true, // 代码块
          table: false, // 表格
          fullscreen: true, // 全屏编辑
          readmodel: true, // 沉浸式阅读
          htmlcode: false, // 展示html源码
          help: false, // 帮助
          /* 1.3.5 */
          undo: true, // 上一步
          redo: true, // 下一步
          trash: true, // 清空
          save: false, // 保存（触发events中的save事件）
          /* 1.4.2 */
          navigation: false, // 导航目录
          /* 2.1.8 */
          alignleft: false, // 左对齐
          aligncenter: false, // 居中
          alignright: false, // 右对齐
          /* 2.2.1 */
          subfield: false, // 单双栏模式
          preview: true, // 预览
        },
      },
      templateContent: "",
      templateMap: new Map(),
    };
  },
  watch: {
    ruleForm: {
      deep: true,
      immediate: true,
      handler(newVal) {
        let {
          receiverOrVchannelId,
          // 0 不排他，1 排他
          exclusive,
          // dc 表单id
          dcFormId,
        } = newVal;
        // 任务是否排他
        this.isExclusive(exclusive);
        // 是否使用DC模板
        this.isDcForm(dcFormId ? true : false);
        // 是否为群会话接收
        this.isGroupChannel(receiverOrVchannelId);
      },
    },
    touchId: {
      deep: true,
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.initOptionData();
          this.initTouchData();
        }
      },
    },
  },
  computed: {},
  methods: {
    isDcForm(data) {
      this.hideProp.content = data;
      this.hideProp.variablesList = !data;
      this.hideProp.dcFormPreview = !data;
    },
    isExclusive(data) {
      this.hideProp.notifyUrl = !data;
    },
    isGroupChannel(data) {
      this.hideProp.vChannelId = data;
      this.hideProp.receiver = !data;
    },
    $imgAdd(pos, $file) {
      let md = this.$refs.markdownEditor;
      if ($file.miniurl) {
        this.message.warning({ message: "暂不支持上传图片，请使用链接插入图片" });
        md.$img2Url(pos, "del this"); //替换url，用以标记待删除的无效图片上传
      }
    },
    //打开链接插入图片
    $toggle_imgLinkAdd(type) {
      let md = this.$refs.markdownEditor;
      md.$children[0].$toggle_imgLinkAdd(type);
    },
    getVariables(data) {
      this.ruleForm.variables = data;
    },
    getRequestData() {
      let {
        exclusive,
        // 回调地址
        notifyUrl,
        // dc表单id
        dcFormId,
        // 接收者
        receiver,
        // true 账号、false 群
        receiverOrVchannelId,
        // dc 会话id
        vChannelId,
        // 内容
        content,
        // 模版变量
        variables,
      } = this.ruleForm;
      let requestData = {
        ...this.ruleForm,
        spaceId: this.$route.params.spaceId,
        notifyUrl: exclusive === 1 ? notifyUrl : "",
        receiver: receiverOrVchannelId ? receiver : "",
        vChannelId: receiverOrVchannelId ? "" : vChannelId,
        content: dcFormId ? "" : content,
        variables: dcFormId ? variables : "",
      };
      return requestData;
    },
    save() {
      if (this.$refs.formRef.submitForm()) {
        //如果存在模板字段列表，为模板变量赋值
        if (this.$refs.variablesListRef) {
          this.$refs.variablesListRef.getVariables();
        }
        // 处理提交字段
        touchInsertApi({
          requestData: this.getRequestData(),
        }).then((res) => {
          let state = this.message.state(res);
          if (!state) return;
          let data = { type: "create", id: res.data.id };
          if (this.touchId) {
            data.type = "edit";
          }
          this.$emit("flushList", data);
        });
      }
    },
    // 预览
    previewTouchSource() {
      previewTouchApi({
        requestData: { ...this.getRequestData(), id: null },
      }).then((res) => {
        if (res.code !== 0) return;
        this.message.success({
          message: this.$t("预览发送成功，请到DC查看详情"),
        });
      });
    },
    getDcFormOption(query, variables) {
      this.optionData.dcFormId = [];
      if (!query) {
        return;
      }
      if (/[^\d]/.test(query)) {
        this.message.error({ message: this.$t("模板ID为整数数字") });
        return;
      }
      dcFormDetailApi({ id: query }).then((res) => {
        if (res.code === 0) {
          let { id, name, json } = res.data;
          this.optionData.dcFormId = [{ label: name, value: id }];
          //设置map
          let value = { content: json, variables: variables };
          this.templateMap.set(id, value);
          if (variables) {
            this.ruleForm.dcFormPreview = json;
          }
        }
      });
    },
    initOptionData() {
      dcSenderListApi().then((res) => {
        this.optionData.msgAccountId = res.data.list.map(function (item, index, array) {
          // 解构赋值
          let { id, name } = item;
          return { label: name, value: id };
        });
      });
    },
    // 编辑时初始化数据
    initTouchData() {
      detailTaskApi({
        requestData: this.touchId,
      }).then((res) => {
        // console.log("res>", res);
        if (!res) return;
        let {
          title,
          followId,
          exclusive,
          notifyUrl,
          dcFormId,
          msgAccountId,
          receiver,
          vChannelId,
          content,
          variables,
        } = res.data;
        this.ruleForm = {
          ...res.data,
          followId: followId == 0 ? "" : followId,
          dcFormId: dcFormId == 0 ? "" : dcFormId,
          receiverOrVchannelId: !vChannelId,
        };
        // 模板数据
        this.getDcFormOption(dcFormId, variables);
      });
    },
  },
  created() {},
  mounted() {
    this.initOptionData();
  },
};
</script>
<style lang="scss" scoped>
.v-note-wrapper {
  z-index: 10 !important;
}
.markdown-body {
  border: 1px solid #dcdfe6 !important;
  box-shadow: rgb(0 0 0 / 10%) 0 0 0 0 !important;
}

.fullscreen {
  z-index: 1501 !important;
}
</style>
